import React, { PureComponent } from 'react'
import { Button, Popconfirm } from 'antd'
import list2tree from 'list2tree'
import {
  BreadcrumbBar,
  InputSearch,
  ProTable,
  ProTableOperate,
  ProTableOptions,
  ProTree,
  searchTreeListByName,
} from '@/components'
import NewModelModal from './newModelModal'
import CheckModelModal from './checkModelModal'
import styles from './index.less'
import {
  deleteModelById,
  getModelById,
  getModelByTblId,
  getSchemas,
  getStorageType,
  getThemeList,
  getThemeMenus,
} from './api'
import { getHashParameterByName } from '@/utils/helper'

const getNavTreeDataFunc = list2tree({
  idKey: 'id',
  parentIdKey: 'pid',
  newKey: {
    key: 'id',
    value: 'id',
    title: 'themeName',
  },
})

const { OperateItem } = ProTableOperate

export default class CommonModel extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      columns: [
        {
          title: '模型中文名称',
          dataIndex: 'cnName',
          width: '18%',
          key: 'cnName',
        },
        {
          title: '模型英文名称',
          // dataIndex: 'enName',
          width: '18%',
          key: 'enName',
          render: ({ enName, schema }) => (
            schema !== null ? `${schema}.${enName}` : enName
          ),
        },
        {
          title: '类型',
          dataIndex: 'tableType',
          width: '10%',
          key: 'tableType',
          render: (text, record, index) => (
            <>
              {
                text === 'MANAGED_TABLE' && '内表'
              }
              {
                text === 'EXTERNAL' && '外表'
              }
              {
                text === 'EXTERNAL_TABLE' && '外表'
              }
              {
                text === 'VIEW' && '视图'
              }
              {
                (text === undefined || text === null) && '--'
              }
            </>
          ),
        },
        {
          title: '密级',
          dataIndex: 'secretLevel',
          width: '10%',
          key: 'secretLevel',
        },
        {
          title: '创建人',
          dataIndex: 'createBy',
          width: '13%',
          key: 'createBy',
        },
        {
          title: '修改时间',
          dataIndex: 'updateTime',
          width: '13%',
          key: 'updateTime',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '13%',
          key: 'operation',
          render: (text, record, index) => (
            <ProTableOptions>
              <span
                onClick={() => {
                  this.checkId(record, this.onCheckClick)
                }}
                key="check"
              >
                查看
              </span>
              <span onClick={() => this.checkId(record, this.onEditClick)} key="edit">编辑</span>
              <Popconfirm
                title="你确定要删除这个模型吗？"
                okText="确定"
                cancelText="取消"
                onConfirm={() => this.checkId(record, this.onDeleteClick)}
                key="delPop"
              >
                <span>删除</span>
              </Popconfirm>
            </ProTableOptions>
          ),
        },
      ],
      treeData: [],
      treeList: [],
      treeDataNew: [],
      selectedKeys: [],
      storageType: '',
      fieldTypes: [],
      schemasOption: [],
      loading: false,
      inputValue: '',
      query: { modelType: props.modelType },
      pid: '',
      modalTreeData: [],
      tableType: '',
    }

    this.newModelModal = React.createRef()
    this.checkModelModal = React.createRef()
  }

  componentDidMount() {
    const searchName = getHashParameterByName('searchName')
    this.getThemeList()
    this.getStorageType()
    this.getSchemas()
    if (searchName) {
      this.setState({
        inputValue: searchName,
      })
    }
  }

  getSchemas() {
    getSchemas().then(
      (res) => {
        this.setState({
          schemasOption: res,
        })
      },
      (error) => {
        console.log(error)
      },
    )
  }

  // 获取主题列表
  getThemeList = () => {
    // 标记每个节点是第几层children
    const signLayerNum = (item, num = 0) => {
      item.layerNum = num
      if (num >= 5) {
        item.icon = true
      }
      if (item.children) {
        item.children.map((child) => {
          const tempNum = num + 1
          signLayerNum(child, tempNum)
        })
      }
    }
    getThemeMenus({ modelType: this.props.modelType }).then(
      (res) => {
        const arr = getNavTreeDataFunc(res)
        // 给tree的数据标上第几层children
        arr.map((item) => {
          signLayerNum(item)
        })
        this.setState({
          treeData: arr,
          treeList: res || [],
          treeDataNew: arr,
        }, () => {
          this.fetchData()
        })
      },
      (error) => {
        console.log(error)
      },
    )

    getThemeList({ modelType: this.props.modelType }).then(
      (res) => {
        const arr = getNavTreeDataFunc(res)
        // 给tree的数据标上第几层children
        arr.map((item) => {
          signLayerNum(item)
        })
        this.setState({
          modalTreeData: arr,
        })
      },
      (error) => {
        console.log(error)
      },
    )
  }

  // 获取存储类型
  getStorageType() {
    getStorageType().then(
      (res) => {
        this.setState({
          storageType: res.type,
          fieldTypes: res.fieldTypes,
        })
      },
      (error) => {
        console.log(error)
      },
    )
  }

  // 编辑按钮回调
  onEditClick = (id) => {
    this.setState({ loading: true })
    getModelById({ modelId: id }).then(
      (res) => {
        res.tableType = this.state.tableType
        this.setState({ loading: false })
        this.newModelModal.current.onEditOpenModal(res)
      },
      (error) => {
        console.log(error)
        this.setState({ loading: false })
      },
    )
  }

  // 查看按钮回调
  onCheckClick = (id) => {
    this.setState({ loading: true })
    getModelById({ modelId: id }).then(
      (res) => {
        this.setState({ loading: false })
        this.checkModelModal.current.openModal(res)
      },
      (error) => {
        console.log(error)
        this.setState({ loading: false })
      },
    )
  }

  // 删除按钮回调
  onDeleteClick = (id) => {
    this.setState({ loading: true })
    deleteModelById({ modelId: id }).then(
      (res) => {
        this.setState({ loading: false })
        this.fetchData()
      },
      (error) => {
        console.log(error)
        this.setState({ loading: false })
      },
    )
  }

  // 判断id是否存在
  checkId = (record, cb) => {
    this.setState({
      tableType: record.tableType,
    })
    if (!record.id) {
      getModelByTblId({ tblId: record.tblId }).then(
        (res) => {
          cb && cb(res.id)
        },
        (error) => {
          console.log(error)
        },
      )
    } else {
      cb && cb(record.id)
    }
  }

  // 新建按钮回调
  showModal = () => {
    const { pid } = this.state
    this.newModelModal.current.openModal(this.state.selectedKeys, pid)
  }

  onSelect = (selectedKeys, info) => {
    const pid = info?.node?.pid
    this.setState({
      selectedKeys,
      pid,
    }, () => {
      this.fetchData()
    })
  }

  fetchData = () => {
    const { selectedKeys, inputValue, pid } = this.state
    const tempQuery = {
      modelType: this.props.modelType,
    }
    if (selectedKeys && selectedKeys.length > 0) {
      tempQuery.themeId = pid === '0' ? '' : selectedKeys[0]
    } else {
      tempQuery.themeId = ''
    }
    if (inputValue && inputValue !== '') tempQuery.search = inputValue
    this.setState({
      query: tempQuery,
    })
  }

  closeCallBack = () => {
    this.fetchData()
  }

  render() {
    const {
      loading, treeData, treeList, treeDataNew, selectedKeys, storageType, fieldTypes, inputValue, schemasOption, modalTreeData,
    } = this.state
    const { modelName, options, menus } = this.props
    return (
      <div className={styles.page_content_with_breadcrumb}>
        <BreadcrumbBar menu={menus} />
        <div className={styles.page_content}>
          <div className={styles.page_content_left}>
            <ProTree
              showLine
              showSearch
              showTitle={false}
              treeData={treeDataNew}
              selectedKeys={selectedKeys}
              onSelect={this.onSelect}
              ref={(dev) => (this.tree = dev)}
              search={(name) => {
                const searchTree = searchTreeListByName(
                  name,
                  treeList,
                  'themeName',
                )
                const treeDataNews = getNavTreeDataFunc(
                  searchTree.result,
                )
                this.setState(
                  {
                    treeDataNew: treeDataNews,
                  },
                  () => {
                    this.tree.onExpand(searchTree.fatchIds)
                  },
                )
              }}
            />
          </div>
          <div className={styles.page_content_right}>
            <ProTableOperate
              toggleOperate={false}
              unfolded
            >
              <OperateItem align="left">
                <InputSearch
                  placeholder="请输入关键词进行搜索"
                  value={inputValue}
                  onChange={(e) => {
                    this.setState({
                      inputValue: e.target.value,
                    })
                  }}
                  onSearch={this.fetchData}
                />
              </OperateItem>
              <OperateItem itemType="btn">
                {
                  [
                    <Button
                      onClick={this.showModal}
                      type="primary"
                      loading={loading}
                      disabled={storageType === ''}
                      key="new"
                    >
                      {`新建${modelName}`}
                    </Button>,
                  ]
                }
              </OperateItem>
            </ProTableOperate>
            <ProTable
              columns={this.state.columns}
              loading={loading}
              url={(this.state.query.themeId || this.state.query.themeId === '') ? '/api/v1/normalization/modeldesign/model/getModelListByType' : null}
              query={this.state.query}
            />
          </div>
        </div>

        <NewModelModal
          modelName={modelName}
          treeOptions={modalTreeData}
          schemasOption={schemasOption}
          options={options}
          ref={this.newModelModal}
          getThemeList={this.getThemeList}
          modelType={this.props.modelType}
          storageType={this.state.storageType}
          closeCallBack={this.closeCallBack}
          fieldTypes={fieldTypes}
          // listDataSecret={listDataSecret || []}
        />

        <CheckModelModal
          ref={this.checkModelModal}
          storageType={this.state.storageType}
          treeOptions={modalTreeData}
          fieldTypes={fieldTypes}
          // listDataSecret={listDataSecret || []}
        />
      </div>
    )
  }
}
